/**
 * Filename: BrowseActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/13 16:24
 */
package com.github.postsanf.yinian.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.pop.PopShareBrowse;
import com.github.postsanf.yinian.adapter.DraweePagerAdapter;
import com.github.postsanf.yinian.bean.YNNativeImage;
import com.github.postsanf.yinian.bean.YNPhoto;
import com.github.postsanf.yinian.bean.YNPicList;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNCommonResponse;
import com.github.postsanf.yinian.utils.Crop;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.ImageUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SnackBarUtils;
import com.github.postsanf.yinian.utils.YNUrlHelper;
import com.github.postsanf.yinian.view.MultiTouchViewPager;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 浏览大图
 */
public class BrowseActivity extends BaseActivity implements View.OnClickListener {
    private Toolbar mToolbar;
    private MultiTouchViewPager vp_browse;                              // 整个切换视图
    private int position;// 位置
    private DraweePagerAdapter mAdapter;                               // 适配器
    private List<String> picUrlsList;                            // 图片数据
    private List<String> picThumb;                            // 图片数据
    private YNStatus mDatas;                                 // 该动态数据
    private SimpleDraweeView iv_vp_bg;
    private RelativeLayout rl_save_img;
    private boolean isShow = false;
    private boolean isFromWall = false;
    private boolean isMe = false;
    private List<YNNativeImage> photosTime = new ArrayList<>();
    private List<YNPhoto> photos = new ArrayList<>();
    private List<YNPicList> ynPicListList = new ArrayList<>();
    private int totalsize = 0;
    private boolean timeWall = false;
    private boolean timeLine = false;
    private PopShareBrowse mPopShareBrowse;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_browse);
        initData();
        initView();
        setData();
    }

    private void initData() {
        mDatas = YNSingleton.getInstance().getCurStatus();
        mPopShareBrowse = new PopShareBrowse(BrowseActivity.this, itemsOnClick, itemsOnTouch);
        mTempDir = new File(Environment.getExternalStorageDirectory(), "yinian/temp");
        if (!(mTempDir.mkdir() || mTempDir.isDirectory())) {
            mTempDir.mkdirs();
        }
        position = getIntent().getIntExtra(CommonConstants.YNPOSITION, 0);
        isMe = getIntent().getBooleanExtra(CommonConstants.YNISME, false);
        isFromWall = getIntent().getBooleanExtra(CommonConstants.YNDATAS, false);
        timeWall = getIntent().getBooleanExtra(CommonConstants.TIMEWALL, false);
        timeLine = getIntent().getBooleanExtra(CommonConstants.TIMELINE, false);
        if (isFromWall) {
            photos = (List<YNPhoto>) getIntent().getSerializableExtra(CommonConstants.YNQNURL);
        }
        if (timeWall) {
            photosTime = (List<YNNativeImage>) getIntent().getSerializableExtra(CommonConstants.YNQNURL);
        }
        if (timeLine) {
            ynPicListList.addAll(mDatas.getPicList());
        }
        picUrlsList = mDatas.getUrl();
        picThumb = mDatas.getThumbnail();
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.browse_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.btn_expend_white);
        vp_browse = (MultiTouchViewPager) findViewById(R.id.vp_browse);
        rl_save_img = (RelativeLayout) findViewById(R.id.rl_save_img);
        iv_vp_bg = (SimpleDraweeView) findViewById(R.id.iv_vp_bg);
        rl_save_img.setOnClickListener(this);
        if (!isFromWall) {
            if (isMe || (mDatas.getPublishUser() != null && mDatas.getPublishUser().getUserid() == application.getCurID()) || String.valueOf(application.getCurID()).equals(getString(R.string.numberofme))) {
                isShow = true;
                invalidateOptionsMenu();
            }
        }
    }

    private void setData() {
        if (isFromWall) {
            mAdapter = new DraweePagerAdapter(this, photos, null, null);
        } else if (timeWall) {
            mAdapter = new DraweePagerAdapter(this, photosTime);
        } else if (timeLine) {
            mAdapter = new DraweePagerAdapter(this, ynPicListList, null);
        } else {
            mAdapter = new DraweePagerAdapter(this, picUrlsList, false);
        }
        vp_browse.setAdapter(mAdapter);
        if (isFromWall) {
            totalsize = photos.size();
        } else if (timeWall) {
            totalsize = photosTime.size();
        } else if (timeLine) {
            totalsize = ynPicListList.size();
        } else {
            totalsize = picUrlsList.size();
        }
        if (totalsize > 1) {
            mToolbar.setTitle((position + 1) + "/" + totalsize);
        } else {
            mToolbar.setTitle(" ");
        }
        vp_browse.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int arg0) {
                int index = arg0 % totalsize;
                mToolbar.setTitle((index + 1) + "/" + totalsize);
                doBlur(index);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
        doBlur(position);
        vp_browse.setCurrentItem(position);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_save_img:
                SnackBarUtils.makeShort(mToolbar, "正在下载...").show();
                downPic(mAdapter.getPic(vp_browse.getCurrentItem()), "yn_" + System.currentTimeMillis() / 1000 + ".jpg");
                Intent statintentbtsave = new Intent(ACTIONs.record);
                statintentbtsave.putExtra("key", "查看大图·保存_4");
                statintentbtsave.putExtra("value", 1);
                sendBroadcast(statintentbtsave);
                break;
        }
    }

    private void downPic(final String url, final String name) {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
        if (!(file.mkdir() || file.isDirectory())) {
            file.mkdirs();
        }
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    URL url1 = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.setRequestMethod("GET");
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        InputStream is = conn.getInputStream();
                        localPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/yinian/YiNian/" + name;
                        f = new File(localPath);
                        if (f.exists()) {
                            f.delete();
                        }
                        FileOutputStream fos = new FileOutputStream(f);
                        int len = 0;
                        byte[] buff = new byte[1024];
                        while ((len = is.read(buff)) != -1) {
                            fos.write(buff, 0, len);
                        }
                        is.close();
                        fos.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                downloadHandler.sendEmptyMessage(3);
                // 其次把文件插入到系统图库
                if (!f.exists())
                    return;
                ContentValues values = new ContentValues(7);
                values.put(MediaStore.Images.Media.TITLE, name);
                values.put(MediaStore.Images.Media.DISPLAY_NAME, ts);
                values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                values.put(MediaStore.Images.Media.DATA, f.getAbsolutePath());
                getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                // 最后通知图库更新
                try {
                    mMediaonnection = new MediaScannerConnection(BrowseActivity.this, new MediaScannerConnection.MediaScannerConnectionClient() {
                        @Override
                        public void onMediaScannerConnected() {
                            mMediaonnection.scanFile(f.getParentFile().getAbsolutePath(), ts);
                        }

                        @Override
                        public void onScanCompleted(String path, Uri uri) {
                            mMediaonnection.disconnect();
                        }
                    });
                    mMediaonnection.connect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private MediaScannerConnection mMediaonnection;

    private void doBlur(int pos) {
        String paths = YNUrlHelper.getBrowseBlur(this, mAdapter.getPic(pos));
        Uri uri = Uri.parse(paths);
        ImageOptHelper.showFrescoBlur(uri, iv_vp_bg, this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_delete, menu);
        MenuItem action_delete_single = menu.findItem(R.id.action_delete_single);
        MenuItem action_delete_all = menu.findItem(R.id.action_delete_all);
        if (isShow) {
            action_delete_single.setVisible(true);
            action_delete_all.setVisible(true);
        } else {
            action_delete_single.setVisible(false);
            action_delete_all.setVisible(false);
        }
        return true;
    }

    private File f;
    private String ts;
    private String imagelocal;
    private String localPath;
    private ProgressDialog mProgressDialog;
    private File mTempDir;
    Handler downloadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 2) {
                mProgressDialog.dismiss();
                beginCrop(Uri.parse("file:///" + localPath));
            } else if (msg.what == 3) {
                Toast.makeText(BrowseActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
            }
        }
    };

    // 开始剪切过程
    private void beginCrop(Uri source) {
        String fileName = "Temp_" + String.valueOf(System.currentTimeMillis()) + ".jpg";
        File cropFile = new File(mTempDir, fileName);
        Uri outputUri = Uri.fromFile(cropFile);
        new Crop(source).output(outputUri).asSquare().setCropType(false).start(this);
    }

    // 处理图像剪切结果
    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == Activity.RESULT_OK) {
            SelectedImg.mSelectedImage.clear();
            imagelocal = ImageUtils.getImageAbsolutePath19(this, Crop.getOutput(result));
            Intent pmINtent = new Intent(BrowseActivity.this, PuzzleMakeActivity.class);
            pmINtent.putExtra("imagelocal", imagelocal);
            pmINtent.putExtra("eventid", String.valueOf(mDatas.getEid()));
            startActivity(pmINtent);
            if (f != null && f.exists()) {
                f.delete();
            }
        } else if (resultCode == Crop.RESULT_ERROR) {
            showToast("处理图片失败");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Crop.REQUEST_CROP:
                handleCrop(resultCode, data);
                break;
        }
    }

    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        public void onClick(View v) {
            mPopShareBrowse.dismiss();
            switch (v.getId()) {
                case R.id.btn_make_puzzle:
                    mProgressDialog = ProgressDialog.show(BrowseActivity.this, "", CommonConstants.TIP_LOAD_DATA);
                    ts = "yn_" + System.currentTimeMillis() + ".jpg";
                    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
                    if (!(file.mkdir() || file.isDirectory())) {
                        file.mkdirs();
                    }
                    localPath = "";
                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            try {
                                URL url1 = new URL(mAdapter.getPic(vp_browse.getCurrentItem()));
                                HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
                                conn.setConnectTimeout(5000);
                                conn.setRequestMethod("GET");
                                int code = conn.getResponseCode();
                                if (code == 200) {
                                    InputStream is = conn.getInputStream();
                                    localPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/yinian/YiNian/" + ts;
                                    f = new File(localPath);
                                    if (f.exists()) {
                                        f.delete();
                                    }
                                    FileOutputStream fos = new FileOutputStream(f);
                                    int len = 0;
                                    byte[] buff = new byte[1024];
                                    while ((len = is.read(buff)) != -1) {
                                        fos.write(buff, 0, len);
                                    }
                                    is.close();
                                    fos.close();
                                    downloadHandler.sendEmptyMessage(2);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();
                    break;
                case R.id.btn_share:
                    if (isFromWall) {
                        Intent intent = new Intent(BrowseActivity.this, BrowseShareActivity.class);
                        intent.putExtra("pic", photos.get(vp_browse.getCurrentItem()).getThumbnail());
                        startActivity(intent);
                    } else if (timeWall) {
                        Intent intent = new Intent(BrowseActivity.this, BrowseShareActivity.class);
                        intent.putExtra("pic", photosTime.get(vp_browse.getCurrentItem()).getThumbnail());
                        startActivity(intent);
                    } else if (timeLine) {
                        Intent intent = new Intent(BrowseActivity.this, BrowseShareActivity.class);
                        intent.putExtra("pic", ynPicListList.get(vp_browse.getCurrentItem()).getThumbnail());
                        startActivity(intent);
                    } else {
                        startActivity(new Intent(BrowseActivity.this, BrowseShareActivity.class).putExtra("pic", picThumb.get(vp_browse.getCurrentItem())));
                    }
                    break;
            }
        }
    };

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_share_single:
                mPopShareBrowse.showAtLocation(BrowseActivity.this.findViewById(R.id.rl_browse_content), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
            // 删除单张照片
            case R.id.action_delete_single:
                android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
                builder.setCancelable(false);
                final android.app.AlertDialog dlg = builder.create();
                dlg.show();
                Window window = dlg.getWindow();
                window.setContentView(R.layout.pub_dialog);
                window.setBackgroundDrawableResource(R.color.transparent);
                WindowManager.LayoutParams layout = dlg.getWindow().getAttributes();
                layout.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 35 * 2);
                dlg.getWindow().setAttributes(layout);
                TextView tt = (TextView) window.findViewById(R.id.pp_title);
                tt.setText("提示");
                TextView content = (TextView) window.findViewById(R.id.pp_content);
                content.setText("确定要删除这张照片吗?");
                TextView cancel = (TextView) window
                        .findViewById(R.id.btn_cancel);
                cancel.setText("取消");
                cancel.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        dlg.cancel();
                    }
                });
                final TextView ok = (TextView) window.findViewById(R.id.btn_ok);
                ok.setText("确定");
                ok.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        dlg.cancel();
                        doDeleteSingle(vp_browse.getCurrentItem());
                    }
                });
                break;
            // 删除整组照片
            case R.id.action_delete_all:
                android.app.AlertDialog.Builder builderall = new android.app.AlertDialog.Builder(this);
                builderall.setCancelable(false);
                final android.app.AlertDialog dlgall = builderall.create();
                dlgall.show();
                Window windowall = dlgall.getWindow();
                windowall.setContentView(R.layout.pub_dialog);
                windowall.setBackgroundDrawableResource(R.color.transparent);
                WindowManager.LayoutParams layoutall = dlgall.getWindow().getAttributes();
                layoutall.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 35 * 2);
                dlgall.getWindow().setAttributes(layoutall);
                TextView ttall = (TextView) windowall.findViewById(R.id.pp_title);
                ttall.setText("提示");
                TextView contentall = (TextView) windowall.findViewById(R.id.pp_content);
                contentall.setText("确定要删除这条动态吗?");
                TextView cancelall = (TextView) windowall
                        .findViewById(R.id.btn_cancel);
                cancelall.setText("取消");
                cancelall.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        dlgall.cancel();
                    }
                });
                final TextView okall = (TextView) windowall.findViewById(R.id.btn_ok);
                okall.setText("确定");
                okall.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        dlgall.cancel();
                        doDeleteStatus();
                    }
                });
                break;
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }


    private View.OnTouchListener itemsOnTouch = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int height = mPopShareBrowse.mMenuView.findViewById(R.id.pop_set_brose_layout).getTop();
            int y = (int) event.getY();
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (y < height) {
                    mPopShareBrowse.dismiss();
                }
            }
            return true;
        }
    };

    // 删除该条动态
    private void doDeleteStatus() {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_EVENT_ID, String.valueOf(mDatas.getEid()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynDeleteEvent))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resDelete = gson.fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resDelete.getCode())) {
                            Intent mIntent = new Intent(ACTIONs.actionStatus);
                            // 同步删除动态
                            mIntent.putExtra(ACTIONs.IsAdd, false);
                            mIntent.putExtra(ACTIONs.StatusId, mDatas.getEid());
                            sendBroadcast(mIntent);
                            sendBroadcast(new Intent(ACTIONs.actionGridWallUpdate));
                            finish();
                            if (getIntent().getBooleanExtra("detail", false)) {
                                sendBroadcast(new Intent(ACTIONs.McardDetailFinish));
                            }
                        } else {
                            showToast("删除失败");
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    // 删除单张图片
    private void doDeleteSingle(final int position) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        String url = "";
        if (isFromWall) {
            url = photos.get(position).getUrl();
        } else if (timeWall) {
            url = photosTime.get(position).getPath();
        } else if (timeLine) {
            url = ynPicListList.get(position).getPoriginal();
        } else {
            url = picUrlsList.get(position);
        }
        Log.i("xjs", "address3===>" + url.split("\\?")[0]);
        mParam.put(CommonConstants.YNS_ADDRESS, url.split("\\?")[0]);
        mParam.put(CommonConstants.YNS_EID, String.valueOf(mDatas.getEid()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynDeleteSinglePhoto))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resDelete = gson.fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resDelete.getCode())) {
                            // 同步删除单张照片
                            if (mAdapter.getCount() <= 1) {
                                Intent delsingleIntent = new Intent(ACTIONs.actionStatus);
                                delsingleIntent.putExtra(ACTIONs.IsAdd, false);
                                delsingleIntent.putExtra(ACTIONs.StatusId, mDatas.getEid());
                                sendBroadcast(delsingleIntent);
                                sendBroadcast(new Intent(ACTIONs.actionAlbumInit));
                                sendBroadcast(new Intent(ACTIONs.actionGridWallUpdate));
                                finish();
                                if (getIntent().getBooleanExtra("detail", false)) {
                                    sendBroadcast(new Intent(ACTIONs.McardDetailFinish));
                                }
                            } else {
                                String url = mAdapter.getPic(position);
                                if (isFromWall) {
                                    photos.remove(position);
                                    mAdapter.removeItem(position);
                                    if (photos.size() > 1) {
                                        totalsize = photos.size();
                                        mToolbar.setTitle((position + 1 > totalsize ? totalsize : position + 1) + "/" + totalsize);
                                    } else {
                                        mToolbar.setTitle(" ");
                                    }
                                } else if (timeWall) {
                                    photosTime.remove(position);
                                    mAdapter.removeItem(position);
                                    if (photosTime.size() > 1) {
                                        totalsize = photosTime.size();
                                        mToolbar.setTitle((position + 1 > totalsize ? totalsize : position + 1) + "/" + totalsize);
                                    } else {
                                        mToolbar.setTitle(" ");
                                    }
                                } else if (timeLine) {
                                    ynPicListList.remove(position);
                                    mAdapter.removeItem(position);
                                    if (ynPicListList.size() > 1) {
                                        totalsize = ynPicListList.size();
                                        mToolbar.setTitle((position + 1 > totalsize ? totalsize : position + 1) + "/" + totalsize);
                                    } else {
                                        mToolbar.setTitle(" ");
                                    }
                                } else {
                                    picUrlsList.remove(position);
                                    mAdapter.removeItem(position);
                                    if (picUrlsList.size() > 1) {
                                        totalsize = picUrlsList.size();
                                        mToolbar.setTitle((position + 1 > totalsize ? totalsize : position + 1) + "/" + totalsize);
                                    } else {
                                        mToolbar.setTitle(" ");
                                    }
                                }
                                Intent mIntent = new Intent(ACTIONs.actionSinglePhoto);
                                mIntent.putExtra(ACTIONs.PhotoPosition, position);
                                mIntent.putExtra(ACTIONs.PhotoUrl, mAdapter.getPic(position));
                                sendBroadcast(mIntent);
                                Intent intent = new Intent(ACTIONs.updataMcardDetailPic);
                                intent.putExtra("position", position);
                                intent.putExtra("url", url);
                                sendBroadcast(intent);
                            }
                        } else {
                            showToast("删除失败");
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    @Override
    protected void onDestroy() {
        Fresco.getImagePipeline().clearCaches();
        System.gc();
        super.onDestroy();
    }

    private long fristTime;

    // 友盟统计
    public void onResume() {
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        super.onResume();
        fristTime = System.currentTimeMillis();
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
        if (getIntent().getStringExtra("type") != null) {
            if (getIntent().getStringExtra("type").equals("time")) {
                Intent intent = new Intent(ACTIONs.record);
                intent.putExtra("key", "查看大图（时间轴）_3");
                intent.putExtra("value", new Long(System.currentTimeMillis() - fristTime).intValue());
                sendBroadcast(intent);

            } else if (getIntent().getStringExtra("type").equals("wall")) {
                Intent intent = new Intent(ACTIONs.record);
                intent.putExtra("key", "查看大图（照片墙）_3");
                intent.putExtra("value", new Long(System.currentTimeMillis() - fristTime).intValue());
                sendBroadcast(intent);
            }
        }

    }
}
